<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()

const readClient = ReadClients[3]
const writeClient = WriteClients[3]

const formRef = ref()
const form = reactive({
  bomNumber: '',
  autoCode: false,
  version: '',
  productName: '',
  productNumber: '',
  specificationModel: '',
  unit: '',
  isDefaultBom: false,
  dailyOutput: undefined as number | undefined,
  status: true,
  remarks: '',
})

const rules = {
  bomNumber: [{ required: true, message: '请输入BOM编号', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  productNumber: [{ required: true, message: '请输入产品编号', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  dailyOutput: [
    { required: true, message: '请输入日产量', trigger: 'blur' },
    { type: 'number', min: 0, message: '日产量不能小于0', trigger: 'blur' }
  ],
}

function generateGuid() {
  // 生成标准 GUID: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = (crypto.getRandomValues(new Uint8Array(1))[0] & 0x0f) >> 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

function handleAuto() {
  if(form.autoCode){
    form.bomNumber = generateGuid()
    formRef.value?.clearValidate('bomNumber')
  }else{
    form.bomNumber = ''
  }
}

async function handleSave() {
  if (!formRef.value) return
  await formRef.value.validate()
  
  try {
    const payload = {
      command: 'CreateBom',
      bomNumber: form.bomNumber,
      isDefaultBom: form.isDefaultBom,
      bomVersion: form.version,
      productName: form.productName,
      productNumber: form.productNumber,
      specificationModel: form.specificationModel,
      unit: form.unit,
      dailyOutput: form.dailyOutput,
      remarks: form.remarks,
      isDelete: false,
      serialNumber: String(Date.now()),
    }
    const res = await WriteClients[3].post('/productwrite/api/Bom/CreateBom', payload)
    if(res && (res.status===200 || res?.data?.code===200 || res?.data?.success)){
      ElMessage.success('保存成功')
      router.push({ name: 'BomInfo' })
    }else{
      throw new Error(res?.data?.message || '保存失败')
    }
  }catch(err:any){
    ElMessage.error(err?.response?.data?.message || err?.message || '保存失败')
  }
}

function handleCancel(){ router.push({ name: 'BomInfo' }) }

const unitOptions = ['件','个','箱','台','米','套','批','瓶']
const versionOptions = ['1.0', '1.1', '1.2', '2.0', '2.1']

// 监听自动编号开关
watch(() => form.autoCode, (v) => {
  if(v){
    form.bomNumber = generateGuid()
  }else{
    form.bomNumber = ''
  }
})
</script>

<template>
  <div class="create-wrap">
    <div class="page-header">
      <h1 class="page-title">新增BOM</h1>
    </div>

    <!-- 基础信息 -->
    <div class="section">
      <div class="section-title">基础信息</div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="base-form">
        <div class="form-grid">
          <div class="form-col">
            <el-form-item label="BOM编号" prop="bomNumber">
              <div class="input-group">
                <el-input v-model="form.bomNumber" placeholder="请输入" />
                <div class="switch-group">
                  <span class="switch-label">系统编号</span>
                  <el-switch v-model="form.autoCode" @change="handleAuto" />
                </div>
              </div>
            </el-form-item>

            <el-form-item label="BOM版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="产品编号" prop="productNumber">
              <el-input v-model="form.productNumber" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择">
                <el-option v-for="u in unitOptions" :key="u" :label="u" :value="u" />
              </el-select>
            </el-form-item>

            <el-form-item label="备注">
              <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入" />
            </el-form-item>
          </div>

          <div class="form-col">
            <el-form-item label="默认BOM" prop="isDefaultBom">
              <el-radio-group v-model="form.isDefaultBom">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>

            <el-form-item label="规格型号">
              <el-input v-model="form.specificationModel" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="日产量" prop="dailyOutput">
              <el-input-number v-model="form.dailyOutput" :min="0" :precision="0" placeholder="请输入" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 底部操作按钮 -->
    <el-card class="action-card">
      <div class="action-buttons">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <el-button size="large" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.create-wrap {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.section {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.base-form {
  padding: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.form-col {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 16px;
}

.switch-group {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.switch-label {
  color: #606266;
  font-size: 14px;
}

.action-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.action-card :deep(.el-card__body) {
  padding: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.action-buttons .el-button {
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header,
  .section {
    padding: 16px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .input-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
